package ch.nostromo.tiffanys.clients.obcreate;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class OBCreate {

  public static void main(String[] args) {
    try {
      File dir = new File("/Users/bvg/Documents/Chess/openings/");
      String[] files = dir.list();

      ArrayList<File> filesToImport = new ArrayList<File>();

      for (int i = 0; i < files.length; i++) {
        if (files[i].endsWith(".pgn")) {
          filesToImport.add(new File(dir.getAbsolutePath(), files[i]));
        }
      }

      ExecutorService es = Executors.newFixedThreadPool(2);

      ArrayList<Future<OBImporterResult>> results = new ArrayList<Future<OBImporterResult>>();

      for (int i = 0; i < filesToImport.size(); i++) {
        results.add(es.submit(new OBImporterCallable(filesToImport.get(i), 10)));
      }

      HashSet<String> resultSet = new HashSet<String>();

      for (int i = 0; i < results.size(); i++) {
        ArrayList<String> openings = results.get(i).get().getResult();
        for (int j = 0; j < openings.size(); j++) {
          resultSet.add(openings.get(j));
        }
      }

      
      
      String[] resultArray = resultSet.toArray(new String[resultSet.size()]);
      Arrays.sort(resultArray);
     

      int openings = 0;

      BufferedWriter br = new BufferedWriter(new FileWriter(new File("resources/engine/opening.data")));

     for (int i = 0; i < resultArray.length; i++) {
        br.write(resultArray[i] + "\n");
        openings++;
      }

      br.close();
      Thread.sleep(3);
      System.out.println("Openings written: " + openings);
      
    } catch (Exception e) {
      e.printStackTrace();
    }
    
  }

}
